package model.workersWithData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.apache.log4j.Logger;

import entities.IMaster;
import entities.IOrder;

public class WorkerWithMaster {

	private static final String MAS_EXISTS = "Sorry, master with this name already exists";
	private static final String MAS_NOT_EXISTS = "Sorry master with this name is absent";
	private static final String EMPTY_COLLEC = "Collection is empty";
	private static final String NOT_MASTER = "Sorry, no master";
	private static final Logger log = Logger.getLogger(WorkerWithMaster.class);

	public static IOrder getOrdersByMaster(String nameMaster,
			ArrayList<IMaster> masList) { 
		try {
			IOrder order = null;
			for (IMaster m : masList) {
				if (m.getNameMaster().equals(nameMaster)) {
					order = m.getOrder();
				}
			}
			if (order != null) {
				return order;
			} else {
				throw new RuntimeException(MAS_NOT_EXISTS);
			}
			
		} catch (NullPointerException n) {
			log.warn(EMPTY_COLLEC);
			throw new RuntimeException(NOT_MASTER);

		}
	}

	public static ArrayList<IMaster> SortMaster(ArrayList<IMaster> masterList,
			Comparator sortBy) { 
		if(!masterList.isEmpty()){
			Collections.sort(masterList, sortBy);
			return masterList;			
		} else {
			log.warn(EMPTY_COLLEC);
			throw new RuntimeException(NOT_MASTER);
			

		}
	}

	public static void addMaster(ArrayList<IMaster> masterList, IMaster master) { 
		try {
			int i = 0;
			for (IMaster m : masterList) {
				if (m.getNameMaster().equals(master.getNameMaster())) {
					i++;
					throw new RuntimeException(MAS_EXISTS);
				}
			}
			if (i == 0) {
				masterList.add(master);
			}
		} catch (NullPointerException n) {
			log.warn(EMPTY_COLLEC);

		}

	}

	public static void deleteMaster(ArrayList<IMaster> masterList,
			String masterName) {
		try {
			ArrayList<IMaster> temp = new ArrayList<IMaster>();
			for (IMaster mas : masterList) {
				if (!mas.getNameMaster().equals(masterName)) {
					temp.add(mas);
				}
			}
			if (temp.size() == masterList.size()) {
				throw new RuntimeException(MAS_NOT_EXISTS);
			} else {
				masterList.clear();
				masterList.addAll(temp);				
			}
		} catch (NullPointerException n) {
			log.warn(EMPTY_COLLEC);

		}
	}

}
